# -*- coding: utf-8 -*-

from igetui.template.igt_transmission_template import *
from igetui.igt_message import *
from igt_push import IGeTui
from igetui.igt_target import *
from tornado import gen
from payload.APNPayload import SimpleAlertMsg
import json
from settings import mysql_app_pool, APPID, APPKEY, MASTERSECRET, HOST


def get_android_template(info_dict):
    template = TransmissionTemplate()
    template.appId = APPID
    template.appKey = APPKEY
    template.transmissionType = 2  # 收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动
    template.transmissionContent = json.dumps(info_dict['content'], ensure_ascii=False)
    template.isRing = True
    template.isVibrate = True
    template.isClearable = True
    return template


def get_ios_template(info_dict):
    template = TransmissionTemplate()
    template.transmissionType = 2
    template.appId = APPID
    template.appKey = APPKEY
    template.transmissionContent = json.dumps(info_dict, ensure_ascii=False)
    template.isRing = True
    template.isVibrate = True
    template.isClearable = True
    # 设置APNs信息
    apnpayload = APNPayload()
    apnpayload.sound = ""
    apnpayload.contentAvailable = 0
    apnpayload.category = ""

    # 简单类型如下设置
    alertMsg = SimpleAlertMsg()
    alertMsg.alertMsg = ""
    # 字典类型如下设置
    alertMsg = DictionaryAlertMsg()
    alertMsg.body = info_dict['title']
    # alertMsg.actionLocKey = 'actionLockey'
    # alertMsg.locKey = 'lockey'
    # alertMsg.locArgs=['loc-args']
    # alertMsg.launchImage = 'launchImage'
    # iOS8.2以上版本支持
    # alertMsg.title = 'Title'
    # alertMsg.titleLocArgs = ['TitleLocArg']
    # alertMsg.titleLocKey = 'TitleLocKey'

    # 可以设置字典类型AlertMsg和简单类型AlertMsg其中之一
    apnpayload.alertMsg = alertMsg

    template.setApnInfo(apnpayload)

    return template


def push_message_to_app(info_dict):
    push = IGeTui(HOST, APPKEY, MASTERSECRET)

    # 新建一个推送模版, 以链接模板为例子，就是说在通知栏显示一条含图标、标题等的通知，用户点击可打开您指定的网页
    template_android = get_android_template(info_dict)
    template_ios = get_ios_template(info_dict)

    message_ios = IGtAppMessage()
    message_ios.data = template_ios
    message_ios.appIdList.extend([APPID])
    message_ios.phoneTypeList.extend(["IOS"])
    message_ios.isOffline = True  # 用户当前不在线时，是否离线存储,可选
    message_ios.offlineExpireTime = 6 * 3600 * 1000  # 离线有效时间，单位为毫秒
    ret_ios = push.pushMessageToApp(message_ios)

    message_android = IGtAppMessage()
    message_android.data = template_android
    message_android.appIdList.extend([APPID])
    message_android.phoneTypeList.extend(["ANDROID"])
    message_android.isOffline = True  # 用户当前不在线时，是否离线存储,可选
    message_android.offlineExpireTime = 6 * 3600 * 1000  # 离线有效时间，单位为毫秒
    ret_android = push.pushMessageToApp(message_android)
    print ret_ios
    print ret_android
    return ret_ios


@gen.coroutine
def get_device_type(client_id):
    sql = "select device_type from app_clientids where client_id = '{}' "
    info = yield mysql_app_pool.get_one(sql.format(client_id), cursor='dict')
    if info:
        res = info['device_type']
    else:
        res = 0
    raise gen.Return(res)


@gen.coroutine
def push_message_to_single(info_dict, client_id):
    print "##################"
    print info_dict
    print "##################"
    push = IGeTui(HOST, APPKEY, MASTERSECRET)

    # 新建一个推送模版, 以链接模板为例子，就是说在通知栏显示一条含图标、标题等的通知，用户点击可打开您指定的网页
    device_type = yield get_device_type(client_id)
    if device_type == 0:
        template = get_android_template(info_dict)
    else:
        template = get_ios_template(info_dict)

    message = IGtListMessage()
    message.data = template
    message.isOffline = True  # 用户当前不在线时，是否离线存储,可选
    message.offlineExpireTime = 6 * 3600 * 1000  # 离线有效时间，单位为毫秒
    target = Target()
    target.appId = APPID
    target.clientId = client_id

    ret = push.pushMessageToSingle(message, target)
    print ret
    raise gen.Return(ret)


@gen.coroutine
def push_message_to_list(info_dict, device_type, client_id_list):
    if client_id_list:
        push = IGeTui(HOST, APPKEY, MASTERSECRET)

        # 新建一个推送模版, 以链接模板为例子，就是说在通知栏显示一条含图标、标题等的通知，用户点击可打开您指定的网页
        if device_type == 0:
            template = get_android_template(info_dict)
        else:
            template = get_ios_template(info_dict)

        message = IGtListMessage()
        message.data = template
        message.isOffline = True  # 用户当前不在线时，是否离线存储,可选
        message.offlineExpireTime = 6 * 3600 * 1000  # 离线有效时间，单位为毫秒
        arr = []
        for item in client_id_list:
            target = Target()
            target.appId = APPID
            target.clientId = item['client_id']
            arr.append(target)
        content_id = push.getContentId(message, 'ToList_pub_consult')
        ret = push.pushMessageToList(content_id, arr)
    else:
        ret = {'result': 'ok'}
    raise gen.Return(ret)
